package com.rover.system.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.grid.DataGrid;
import com.rover.system.entity.Department;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.grid.Page;
import com.rover.system.dao.BaseDao;


@Service("departmentService")
@Transactional
public class DepartmentService extends BaseService {

    @Autowired
    private BaseDao dao;

    @Transactional(readOnly = true)
    public DataGrid query(Page page, Map<String, Object> params, String hql) {
        DataGrid dataGrid = new DataGrid();
        List<Department> departments = new ArrayList<Department>();
        if (StringUtils.isNotBlank(hql)) {
            hql = "from Department " + hql;
            dataGrid.setTotalCount(dao.countHql("select count(*) " + hql, params));
            departments = dao.findPageHql(hql, params, page.getPageNo(), page.getPageSize());
        } else {
            hql = "from Department";
            dataGrid.setTotalCount(dao.countHql("select count(*) " + hql,null));
            departments = dao.findPageHql(hql, page.getPageNo(), page.getPageSize());
        }
        Department t = null;
        for (Department department : departments) {
            t = department.getpDepartment();
            if (t != null) {
                t.setpDepartment(null);
                t.setDepartments(null);
            }
            department.setDepartments(null);
        }
        dataGrid.setResult(departments);
        return dataGrid;
    }

    @Transactional(readOnly = true)
    public void deleteT(String deptCode) {
    	 Map<String, Object> params = new HashMap<String, Object>();
		    params.put("deptCode",  deptCode+"%");
        dao.executeHql("delete from Department where deptCode like :deptCode",params);
    }

    @Transactional(readOnly = true)
    public List<Department> getList() {
        return dao.findHql("from Department dept where dept.pDepartment is null",null);
    }

    @Transactional

    public void save(Department department) {
        if (department.getId() == null) {
            department.setDeptCode(getNextCode(department.getpDeptCode()));
            Department pDepartment = null;
            List<Department> li = dao.findHql("from Department where deptCode='"+department.getpDeptCode()+"'",null);
            if (li.size() > 0) {
                pDepartment = li.get(0);
            }
            department.setpDepartment(pDepartment);
        }
        dao.saveOrUpdate(department);
    }

    @Transactional

    public void update(Department department) {
        Department saveDept = dao.get(Department.class, department.getId());
        saveDept.setRemark(department.getRemark());
        saveDept.setDeptName(department.getDeptName());
        saveDept.setDeptSn(department.getDeptSn());
        //获取父节点
        String strT = "";
        if (saveDept.getpDepartment() != null) {
            strT = saveDept.getpDepartment().getDeptCode();
        }
        if (department.getpDeptCode().equals(strT)) {
            dao.update(saveDept);
        } else {
            //新的CodeName
            String newDeptCode = getNextCode(department.getpDeptCode());
            List<Department> li = dao.findHql("from Department where deptCode='"+ department.getpDeptCode()+"'",null);
            Department pDepartment = null;
            if (li.size() > 0) {
                pDepartment = li.get(0);
            }
            saveDept.setpDepartment(pDepartment);
            saveDept.setDeptCode(newDeptCode);
            dao.update(saveDept);
            dao.executeHql("update Department SET deptCode=concat('" + newDeptCode + "',substring(deptCode," + department.getDeptCode().length() + "+1,length(deptCode))) where substring(deptCode,1,length('" + department.getDeptCode() + "'))='" + department.getDeptCode() + "'",null);

        }

    }

    /// <summary>
    /// 取得下一个部门的编号
    /// </summary>
    /// <param name="con"></param>
    /// <param name="ParentDeptCode"></param>
    /// <returns></returns>
    private String getNextCode(String ParentDeptCode) {
        String SQL = "select max(substring(deptCode,(length(deptCode)-3+1),3)) from Department where 1=1  ";

        if (ParentDeptCode == null || ParentDeptCode == "") {
            SQL += " and length(deptCode)=3 ";
        } else {
            SQL += " and length(deptCode)=" + (ParentDeptCode.length() + 3) + " and substring(deptCode,1," + ParentDeptCode.length() + ")='" + ParentDeptCode + "' ";
        }
        Object MaxID = dao.uniqueResultHql(SQL,null);

        if (MaxID == null) {
            if (ParentDeptCode == "")
                return "001";
            else
                return ParentDeptCode + "001";
        } else {
            if (ParentDeptCode == "")
                return String.format("%03d", (Long.valueOf(MaxID.toString()) + 1l));
            else
                return ParentDeptCode + String.format("%03d", (Long.valueOf(MaxID.toString()) + 1l));
        }

    }

}
